﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using TeamsPortal.DataAccess;
using TeamsPortal.ServiceClient;
using TeamsPortal.Validation;
using TeamsPortal.Web.Controllers.Filters;
using TeamsPortal.Web.Controllers.Helpers;
using TeamsPortal.Web.Controllers.Models;

namespace TeamsPortal.Web.Controllers
{
	public class UsersController : BaseController
	{
        private readonly ITopicsServiceClient _topicServiceClient;

        public UsersController(ITopicsServiceClient topicServiceClient)
        {
            _topicServiceClient = topicServiceClient;
        }

		public ActionResult Detail(int id)
		{
            User user = UsersServiceClient.Get(id);
			if (user == null)
			{
				return ResultHelper.NotFoundResult(this);
			}
			//Get posted topics
            ViewData["Topics"] = _topicServiceClient.GetByUser(id, Role);

			return View(user);
		}

		[RequireAuthorization(UserRole.Admin)]
		public ActionResult List(string userName, int page)
		{
			List<User> users = null;
			if (String.IsNullOrEmpty(userName))
			{
                users = UsersServiceClient.GetAll();
			}
			else
			{
                users = UsersServiceClient.FindByName(userName);
			}
            foreach (User user in users)
            {
                Guid providersId;
                //if asp.net membership
                if (Guid.TryParse(user.ProviderId, out providersId))
                {
                    MembershipUser membershipUser = Membership.GetUser(providersId);
                    if (membershipUser != null)
                    {
                        user.LastActivityDate = membershipUser.LastActivityDate;
                    }
                }
            }
			ViewBag.UserName = userName;
			ViewBag.Page = page;

			return View(users);
		}

		public ActionResult MessagesByUser(int id)
		{
            User user = UsersServiceClient.Get(id);
			if (user == null)
			{
				return ResultHelper.NotFoundResult(this);
			}
			//Get posted messages (ordered 
            List<Topic> topics = _topicServiceClient.GetTopicsAndMessagesByUser(id);
			return View(false, topics);
		}

		#region Edit
                
        [RequireAuthorization]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Edit(int id)
		{
			if (this.User.Id != id)
			{
				//Maybe handle a moderator/admin users
				return ResultHelper.ForbiddenResult(this);
			}
            User user = UsersServiceClient.Get(id);
			return View(user);
		}

		[RequireAuthorization]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(int id, [Bind(Prefix = "")]User user)
		{
			if (this.User.Id != id)
			{
				//Future: Maybe handle a moderator/admin users
				return ResultHelper.ForbiddenResult(this);
			}
			try
			{
				user.Id = id;
                UsersServiceClient.Edit(user);
				#region Update membership data
				if (Session.User.Provider == AuthenticationProvider.Membership && !String.IsNullOrEmpty(user.Email))
				{
					var membershipUser = Membership.GetUser();
					membershipUser.Email = user.Email;
					Membership.UpdateUser(membershipUser);
				}
				#endregion
				#region Adapt values
				User.UserName = user.UserName;
				User.Email = Utils.EmptyToNull(user.Email);
				#endregion
				return RedirectToAction("Detail", new { id = id });
			}
			catch (ValidationException ex)
			{
				this.AddErrors(this.ModelState, ex);
			}
			return View(user);
		}
		#endregion

		#region Promote / Demote / Delete
		[RequireAuthorization(UserRole.Admin)]
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Promote(int id, string searched)
		{
            UsersServiceClient.Promote(id);
			return RedirectToAction("List", new
			{
				userName = searched,
				page = 0
			});
		}

		[RequireAuthorization(UserRole.Admin)]
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Demote(int id, string searched)
		{
            UsersServiceClient.Demote(id);
			return RedirectToAction("List", new
			{
				userName = searched,
				page = 0
			});
		}

		[RequireAuthorization(UserRole.Admin)]
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Delete(int id, string searched)
		{
            UsersServiceClient.Delete(id);
			return RedirectToAction("List", new
			{
				userName = searched,
				page = 0
			});
		}
		#endregion

        [RequireAuthorization]
        public ActionResult EditAvatar(int userId, string redirect)
        {
            if (userId != User.Id && !User.IsAdmin)
            {
                return ResultHelper.ForbiddenResult(this);
            }

            var model = new UploadImageModel() { RedirectUrl = redirect };
            if (Request.Browser.Browser == "IE")
                return View("EditAvatarIE", model);
            else
                return View(model);
        }
	}
}